package cn.wolfcode.crm.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;

@Controller
public class RandomCodeController {
    private static final long serialVersionUID = 1L;

    //生成图片内容，把图片内容响应回去
    @RequestMapping("/rand")
    public String randomCode(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

        // 生成随机数
        String randomCode = UUID.randomUUID().toString().substring(0, 5);

        // 把随机数放进 Session中
        req.getSession().setAttribute("RANDOMCODE_IN_SESSION", randomCode);

        // 创建图片对象
        int width = 80;
        int height = 40;
        int imageType = BufferedImage.TYPE_INT_RGB;
        BufferedImage image = new BufferedImage(width, height, imageType);

        // 画板
        Graphics g = image.getGraphics();
        g.setColor(Color.cyan);
        // 绘制一个实心的矩形
        g.fillRect(0, 0, width - 0, height - 0);

        // 把随机数画进图片中
        g.setColor(Color.red); // 设置随机数的颜色
        Font font = new Font("宋体", Font.BOLD + Font.ITALIC, 20);
        g.setFont(font); // 设置随机数的字体和大小
        g.drawString(randomCode, 10, 28);
        // 干扰线
        g.setColor(Color.gray);
        Random r = new Random();
        for (int i = 0; i < 100; i++) {
            g.fillRect(r.nextInt(width), r.nextInt(height), 1, 1);
        }

        // 关闭
        g.dispose();
        // 把图片对象以流的方式保存出去
        ImageIO.write(image, "jpg", resp.getOutputStream());
        return null;
    }
}
